﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
 
public class ExcelDataBase<T> : ScriptableObject where T : ExcelItemBase
{
    public T[] items;
    // 每次调用GetExcelItem都会填充字典，提高之后每次获取同一Item的性能
    public Dictionary<int, T> itemDic;
    
    /// <summary>
    /// 获取指定Item（下次访问会加速）
    /// </summary>
    /// <param name="targetId"></param> 标识Id
    /// <returns></returns>
    public T GetExcelItem(int targetId)
    {
        if (itemDic == null)
        {
            itemDic = new Dictionary<int, T>();
        }
        else
        {
            if (itemDic.ContainsKey(targetId))
                return itemDic[targetId];
        }
        if(items != null && items.Length > 0)
        {
            T tempItem = GetExcelItemLinq(targetId);
            itemDic.Add(targetId, tempItem);
            return tempItem;
        }
        return null;
    }

    /// <summary>
    /// 获取指定Item
    /// </summary>
    /// <param name="targetId"></param> 标识Id
    /// <returns></returns>
    public T GetExcelItemLinq(int targetId)
    {
        if(items != null && items.Length > 0)
        {
            return items.FirstOrDefault(item => item.Id == targetId);
        }
        return null;
    }
    
    

    public T[] GetAllItems()
    {
        return items;
    }
}

//所有数据第一列一定要是 Id
public class ExcelItemBase
{
    public static string necessaryId = "Id";
    
    public int Id;
}